package untils

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
)

//  把所有的服务注册到consul里面统一管理
// 在consul中有健康检查 你可以监控到各个服务的状态
//  在consul中找到对应的服务

// Client 封装了Consul客户端的操作
type Client struct {
	client *api.Client
}

// 传参和返参

func NewConsulClient(host string, port int32) *Client {
	config := api.DefaultConfig()
	config.Address = fmt.Sprintf("%s:%d", host, port)
	client, _ := api.NewClient(config)
	return &Client{
		client: client,
	}
}

type ConsulRegister struct {
	ID      string
	Name    string
	Tags    []string
	Address string
	Port    int
}

// 注册接口

func (c *Client) Register(register ConsulRegister) error {
	registration := new(api.AgentServiceRegistration)
	registration.ID = register.ID
	registration.Tags = register.Tags
	registration.Name = register.Name
	registration.Address = register.Address
	registration.Port = register.Port
	err := c.client.Agent().ServiceRegister(registration)
	return err
}

// 注销接口

func (c *Client) DeRegister(serviceId string) error {
	err := c.client.Agent().ServiceDeregister(serviceId)
	return err
}

func (c *Client) Services() map[string]*api.AgentService {
	service, err := c.client.Agent().Services()
	if err != nil {
		zap.L().Error(fmt.Sprintf("get All consul services failed:%v", err))
		return nil
	}
	return service
}

func (c *Client) ServicesWithFilter(filter string) map[string]*api.AgentService {
	service, err := c.client.Agent().ServicesWithFilter(filter)
	if err != nil {
		zap.L().Error(fmt.Sprintf("filter this services failed:%v", err))
		return nil
	}
	return service
}
